package com.example.diancai.response.base;

import com.example.diancai.consts.ResponseCode;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import org.slf4j.MDC;

@Data
@Builder
@AllArgsConstructor
public class Result<T> {
    /**
     * 请求id
     */
    private String requestId;
    /**
     * 响应code (200成功)
     */
    private int code;
    /**
     * 是否成功
     */
    private boolean success;
    /**
     * 提示信息
     */
    private String message;
    /**
     * 消息体
     */
    private T data;


    public Result() {
        setRequestId(MDC.get("requestId"));
    }

    public Result(boolean success) {
        this.success = success;
        this.code = success ? ResponseCode.success.code : ResponseCode.fail.code;
        setRequestId(MDC.get("requestId"));
    }

    public Result(boolean success, String message) {
        this.success = success;
        this.code = success ? ResponseCode.success.code : ResponseCode.fail.code;
        this.message = message;
        setRequestId(MDC.get("requestId"));
    }

    public Result(boolean success, String message, T data) {
        this.success = success;
        this.code = success ? ResponseCode.success.code : ResponseCode.fail.code;
        this.message = message;
        this.data = data;
        setRequestId(MDC.get("requestId"));
    }


    public static Result success() {
        return new Result<String>(true);
    }

    public static Result success(String message) {
        return new Result<String>(true, message);
    }


    public static Result success(String message, Object data) {
        return new Result(true, message, data);
    }

    public static Result fail() {
        return new Result<String>(false);
    }

    public static Result fail(String message) {
        return new Result(false, message);
    }

    public static Result responseCode(ResponseCode responseCode) {
        Result result = new Result();
        result.setSuccess(false);
        if(responseCode.getCode() == 200){
            result.setSuccess(true);
        }
        result.setCode(responseCode.getCode());
        result.setMessage(responseCode.getMessage());
        return result;
    }


    public static Result fail(String message, Object data) {
        return new Result(false, message, data);
    }

}
